//index.js
const app = getApp()
const db = wx.cloud.database()
import Toast from '../../dist/toast/toast';
import Notify from '../../dist/notify/notify';

Page({
  data: {
    username: '',
    password: '',
    addusername: '',
    addpassword: '',
    usernamecontrastlength: 0,
    registerbutvalue: 0,
    loading: false,
    UserInfo: {},
    phoneNumber: '',
    verifyCode: '',
    showVerifyCode: false,
    sendingSms: false,
    cooldown: 0,
    timer: null
  },

  onLoad: function (options) {
  },

  onUnload: function() {
    // 页面卸载时清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 手机号输入
  phoneNumberInput(e) {
    this.setData({
      phoneNumber: e.detail
    });
  },

  // 验证码输入
  verifyCodeInput(e) {
    this.setData({
      verifyCode: e.detail
    });
  },

  // 获取验证码
  getVerifyCode() {
    const phoneNumber = this.data.phoneNumber;
    
    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      Notify({ type: 'danger', message: '请输入正确的手机号' });
      return;
    }

    this.setData({ sendingSms: true });

    // 调用云函数发送验证码
    wx.cloud.callFunction({
      name: 'sendSms',
      data: {
        phoneNumber: phoneNumber
      }
    }).then(res => {
      if (res.result && res.result.success) {
        this.setData({
          showVerifyCode: true,
          cooldown: 60
        });
        
        // 开始倒计时
        const timer = setInterval(() => {
          if (this.data.cooldown > 0) {
            this.setData({
              cooldown: this.data.cooldown - 1
            });
          } else {
            clearInterval(timer);
          }
        }, 1000);
        
        this.setData({ timer });
        
        Notify({ type: 'success', message: '验证码已发送' });
      } else {
        Notify({ type: 'danger', message: '验证码发送失败，请重试' });
      }
    }).catch(err => {
      console.error('发送验证码失败：', err);
      Notify({ type: 'danger', message: '验证码发送失败，请重试' });
    }).finally(() => {
      this.setData({ sendingSms: false });
    });
  },

  // 验证手机号和验证码
  verifyPhoneNumber() {
    return new Promise((resolve, reject) => {
      if (!this.data.phoneNumber || !this.data.verifyCode) {
        Notify({ type: 'danger', message: '请输入手机号和验证码' });
        reject(new Error('手机号或验证码为空'));
        return;
      }

      wx.cloud.callFunction({
        name: 'verifySms',
        data: {
          phoneNumber: this.data.phoneNumber,
          code: this.data.verifyCode
        }
      }).then(res => {
        if (res.result && res.result.success) {
          resolve(true);
        } else {
          Notify({ type: 'danger', message: '验证码错误' });
          reject(new Error('验证码错误'));
        }
      }).catch(err => {
        console.error('验证失败：', err);
        Notify({ type: 'danger', message: '验证失败，请重试' });
        reject(err);
      });
    });
  },

  // 修改注册函数
  register: function () {
    if (!this.data.username || !this.data.password) {
      Notify({ type: 'danger', message: '请填写用户名及密码' });
      return;
    }

    this.verifyPhoneNumber().then(() => {
      db.collection('test').get().then(res => {
        if (res.data.filter(e => e.username === this.data.username).length === 0) {
          this.setData({ loading: true });
          
          db.collection('test').add({
            data: {
              username: this.data.username,
              password: this.data.password,
              phoneNumber: this.data.phoneNumber,
              createTime: new Date()
            }
          }).then(() => {
            Notify({ type: 'success', message: '注册成功' });
            this.setData({
              loading: false,
              username: '',
              password: '',
              phoneNumber: '',
              verifyCode: '',
              showVerifyCode: false
            });
            
            setTimeout(() => {
              this.setData({ registerbutvalue: 0 });
            }, 1200);
          }).catch(err => {
            console.error('注册失败：', err);
            this.setData({ loading: false });
            Notify({ type: 'danger', message: '注册失败，请重试' });
          });
        } else {
          Notify({ type: 'danger', message: '用户名已存在' });
        }
      });
    }).catch(() => {
      // 验证码验证失败的处理已在 verifyPhoneNumber 中完成
    });
  },

  // 跳转到登录页面
  signin: function () {
    wx.navigateTo({
      url: '../login/login'
    });
  },

  // 保留原有的其他函数
  uservalue: function (e) {
    this.setData({
      username: e.detail
    });
    db.collection('test').get().then(res => {
      if (res.data.filter(e => e.username === this.data.username).length === 0) {
        this.setData({
          usernamecontrastlength: 1
        });
      } else {
        this.setData({
          usernamecontrastlength: 2
        });
      }
    });
  },

  passwordvalue: function (e) {
    this.setData({
      password: e.detail
    });
  },

  adduservalue: function (e) {
    this.setData({
      addusername: e.detail
    });
  },

  addpasswordvalue: function (e) {
    this.setData({
      addpassword: e.detail
    });
  },

  registerbuts: function () {
    this.setData({
      registerbutvalue: 1
    });
  },

  registers: function () {
    this.setData({
      registerbutvalue: 0
    });
  },
  
  onShow: function() {
    // 更新自定义tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }
  }
});
